package graduationorder.graduationorder.service.impl;

import graduationorder.graduationorder.domain.CustomerService;
import graduationorder.graduationorder.domain.User;
import graduationorder.graduationorder.error.BusinessException;
import graduationorder.graduationorder.error.EmBusinessException;
import graduationorder.graduationorder.mapper.UserMapper;
import graduationorder.graduationorder.result.CommonReturnType;
import graduationorder.graduationorder.service.UserService;
import graduationorder.graduationorder.service.vo.AuthUser;
import graduationorder.graduationorder.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;

import static graduationorder.graduationorder.util.Const.AUTH_ADMIN;
import static graduationorder.graduationorder.util.Const.AUTH_NORMAL;

/**
 * @author Mzk
 * @version 1.0
 * @description: 用户相关接口
 * @date 2024/8/3 下午 12:51
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public CommonReturnType login(String userName, String password) throws BusinessException {
        if (userName == null || userName.equals("") || password == null || password.equals("")){
            throw new BusinessException(EmBusinessException.PARAMETER_VALIDATION_ERROR);
        }
        User user = userMapper.getUserByEmployeeId(userName);
        if (user == null){
            throw new BusinessException(EmBusinessException.USER_NON_EXISTENT);
        }
        if (!password.equals(user.getPassword())) throw new BusinessException(EmBusinessException.PARAMETER_VALIDATION_ERROR);
        HashMap<String, String> authMap = new HashMap<>();
        authMap.put("id",user.getId().toString());
        authMap.put("userName",user.getUserName());
        authMap.put("employeeId",user.getEmployeeId());
        authMap.put("authName",user.getAuthName());
        authMap.put("auth",user.getAuth());
        authMap.put("contactInfo",user.getContactInfo());
        String token = JWTUtils.getToken(authMap);
        HashMap<String, String> authUser = new HashMap<>();
        authUser.put("jwt",token);
        authUser.put("auth",user.getAuth());
        return CommonReturnType.create(authUser);
    }

    @Override
    @Transactional
    public CommonReturnType increaseUser(User addUser, String token) throws BusinessException {
        AuthUser user = JWTUtils.getAuthedUser(token);
        if (!user.getAuth().equals(AUTH_ADMIN)) throw new BusinessException(EmBusinessException.USER_AUTHORIZATION_EXCEPTION.setErrorMsg("权限不足"));
        addUser.setAuth(AUTH_NORMAL);
        int i;
        try {
            i = userMapper.increaseUser(addUser);
        } catch (Exception e) {
            throw new BusinessException(EmBusinessException.SERVER_ERROR.setErrorMsg("员工编号不能重复"));
        }
        i += userMapper.increaseUserInfo(addUser);
        if (i <= 0) throw new BusinessException(EmBusinessException.SERVER_ERROR);
        return CommonReturnType.create(addUser.getEmployeeId());
    }

    @Override
    public CommonReturnType queryUser(String userName, String employeeId, String token) throws BusinessException {
        AuthUser user = JWTUtils.getAuthedUser(token);
        if (user.getAuth().equals(AUTH_ADMIN)){
            ArrayList<User> users = userMapper.queryUser4Admin(userName, employeeId);
            return CommonReturnType.create(users);
        }
        if (user.getAuth().equals(AUTH_NORMAL)){
            User onlySelf = userMapper.queryUser4Normal(user.getEmployeeId());
            return CommonReturnType.create(onlySelf);
        }
        return CommonReturnType.create("");
    }

    @Override
    @Transactional
    public CommonReturnType updateUser(User updateUser, String token) throws BusinessException {
        if (updateUser.getId() == null) throw new BusinessException(EmBusinessException.PARAMETER_VALIDATION_ERROR.setErrorMsg("用户ID不能为空"));
        AuthUser user = JWTUtils.getAuthedUser(token);
        if (updateUser.getEmployeeId() == null || updateUser.getEmployeeId().equals("")){
            User userEmployee = userMapper.getUserById(updateUser.getId());
            updateUser.setEmployeeId(userEmployee.getEmployeeId());
        }
        User queriedUser = this.userMapper.getUserById(updateUser.getId());
        CustomerService customerService = this.userMapper.getCustomerServiceInfoByName(queriedUser.getEmployeeId());
        if (customerService == null) throw new BusinessException(EmBusinessException.PARAMETER_VALIDATION_ERROR.setErrorMsg("参数完整性异常"));
        int i = -1;
        if (user.getAuth().equals(AUTH_ADMIN)){
            try {
                i = userMapper.updateUser(updateUser);
            } catch (Exception e) {
                throw new BusinessException(EmBusinessException.SERVER_ERROR.setErrorMsg("员工编号不能重复"));
            }
            if (!(updateUser.getContactInfo() == null) || !updateUser.getContactInfo().equals("")){
                updateUser.setId(customerService.getId());
                i += userMapper.updateUserInfo(updateUser);
            }
        }
        if (user.getAuth().equals(AUTH_NORMAL)) {
            if (!user.getId().equals(updateUser.getId())) throw new BusinessException(EmBusinessException.USER_AUTHORIZATION_EXCEPTION.setErrorMsg("权限不足"));
            try {
                i = this.userMapper.updateUser(updateUser);
            } catch (Exception e) {
                throw new BusinessException(EmBusinessException.SERVER_ERROR.setErrorMsg("员工编号不能重复"));
            }
            if (!(updateUser.getContactInfo() == null) || !updateUser.getContactInfo().equals("")){
                updateUser.setId(customerService.getId());
                i += userMapper.updateUserInfo(updateUser);
            }
        }
        if (i <= 0) throw new BusinessException(EmBusinessException.SERVER_ERROR);
        return CommonReturnType.create("更新成功");
    }

    @Override
    @Transactional
    public CommonReturnType deleteUser(Integer userId, String token) throws BusinessException {
        if (userId == null) throw new BusinessException(EmBusinessException.PARAMETER_VALIDATION_ERROR.setErrorMsg("用户ID不能为空"));
        AuthUser user = JWTUtils.getAuthedUser(token);
        User userEmployee = userMapper.getUserById(userId);
        if (!user.getAuth().equals(AUTH_ADMIN)) throw new BusinessException(EmBusinessException.USER_AUTHORIZATION_EXCEPTION.setErrorMsg("权限不足"));
        int i = userMapper.deleteUser(userId);
        if (userEmployee == null) throw new BusinessException(EmBusinessException.PARAMETER_VALIDATION_ERROR.setErrorMsg("用户信息完整性异常"));
        i += userMapper.deleteUserInfo(userEmployee.getEmployeeId());
        if (i <= 0) throw new BusinessException(EmBusinessException.SERVER_ERROR);
        return CommonReturnType.create("操作成功");
    }

    @Override
    public CommonReturnType modifyPassword(String employeeId, String password, String newPassword) throws BusinessException {
        if (employeeId == null ||employeeId.equals("")
                || password == null || password.equals("")
                || newPassword ==null || newPassword.equals("")
        ) throw new BusinessException(EmBusinessException.PARAMETER_VALIDATION_ERROR);
        User user = userMapper.getUserByEmployeeId(employeeId);
        if (user == null){
            throw new BusinessException(EmBusinessException.USER_NON_EXISTENT);
        }
        if (!password.equals(user.getPassword())) throw new BusinessException(EmBusinessException.PARAMETER_VALIDATION_ERROR.setErrorMsg("旧密码不正确"));
        int i = userMapper.modifyPassword(employeeId, newPassword);
        if (i <= 0) throw new BusinessException(EmBusinessException.SERVER_ERROR);
        return CommonReturnType.create("操作成功");
    }
}

